package com.hubujun.driverlicense.util;

import android.app.ActivityManager;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.content.pm.ProviderInfo;
import android.content.pm.ResolveInfo;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.os.Debug;
import android.telephony.TelephonyManager;

import com.hubujun.driverlicense.ApplicationContext;
import com.hubujun.driverlicense.R;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 手机信息管理工具
 *
 */
public class MobileUtils {

    public static final String PUBLIC_SIGN = "9ae28d0d672e7a7ea570d11508206313";

    public static final String AMAZON_SIGN = "271d184c94be49c78976f52c3f012afb";

    public static final String PACKAGE_NAME = "com.hubujun.driverlicense";

    public static final String DEFAULT_MODEL = "DLPhone";

    private static Boolean IsOrignal;

    public static String getPhoneNo(Context context) {
        TelephonyManager tm = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
        return tm.getLine1Number();
    }

    /**
     * 取得 android 版本
     */
    public static String getAndroidVersionNum() {
        return Build.VERSION.SDK;
    }

    /**
     * 获取手机型号品牌Model
     */
    public static String getPhoneModel() {
        String model = Build.MODEL;
        if (TextUtils.isNullOrEmpty(model)) {
            return DEFAULT_MODEL;
        }
        return model;
    }

    /**
     * 取得手机厂商
     */
    public static String getPhoneManufacturer() {
        return Build.MANUFACTURER;
    }

    /**
     * 取得 设备代码
     */
    public static String getPhoneDeviceNum() {
        return Build.DEVICE;
    }

    public static String getPhoneArgumentByName(String name) {
        Class<Build> clasz = Build.class;
        java.lang.reflect.Field field;
        try {
            field = clasz.getField(name);
            return (String) field.get(new Build());
        } catch (Exception e) {
            Ln.e(e, "getPhoneArgumentByName----exception--");
        }
        return "";
    }

    public static String getVersionNameFromManifest(Context context) {
        String versionName = "";
        try {
            versionName = context.getPackageManager().getPackageInfo(context.getPackageName(), 0).versionName;
        } catch (NameNotFoundException e) {
            Ln.e(e);
        }
        return versionName;
    }

    public static int getVersionCodeFromManifest(Context context) {
        int versionCode = 0;
        try {
            versionCode = context.getPackageManager().getPackageInfo(context.getPackageName(), 0).versionCode;
        } catch (NameNotFoundException e) {
            Ln.e(e);
        }
        return versionCode;
    }

    public static String getMetaDataByName(String metaname) {
        ApplicationInfo info;
        try {
            Context context = ApplicationContext.getContext();
            info = context.getPackageManager().getApplicationInfo(context.getPackageName(), PackageManager.GET_META_DATA);
            return String.valueOf(info.metaData.get(metaname));
        } catch (Exception e) {
            Ln.e(e);
        }
        return "";
    }

    public static void createShortcut(Context context, String className) {
        // 快捷方式要启动的Activity
        Intent target = new Intent(Intent.ACTION_MAIN);
        target.setClassName(context, className);
        target.addCategory(Intent.CATEGORY_LAUNCHER);

        // 动态生成快捷方式
        Intent shortcutIntent = new Intent("com.android.launcher.action.INSTALL_SHORTCUT");
        shortcutIntent.putExtra(Intent.EXTRA_SHORTCUT_NAME, context.getResources().getString(R.string.app_name));
        shortcutIntent.putExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE, Intent.ShortcutIconResource.fromContext(context, R.mipmap.ic_launcher));
        shortcutIntent.putExtra("duplicate", false);
        shortcutIntent.putExtra(Intent.EXTRA_SHORTCUT_INTENT, target);

        // 利用receiver通知系统创建快捷方式
        ApplicationContext.getContext().sendBroadcast(shortcutIntent);

    }

    private static String getAuthorityFromPermission(Context context, String permission) {
        if (TextUtils.isEmpty(permission)) {
            return null;
        }
        List<PackageInfo> packs = context.getPackageManager().getInstalledPackages(PackageManager.GET_PROVIDERS);
        if (packs == null) {
            return null;
        }
        for (PackageInfo pack : packs) {
            ProviderInfo[] providers = pack.providers;
            if (providers != null) {
                for (ProviderInfo provider : providers) {
                    if (provider.readPermission != null && provider.readPermission.endsWith(permission)) {
                        return provider.authority;
                    }
                    if (provider.writePermission != null && provider.writePermission.endsWith(permission)) {
                        return provider.authority;
                    }
                }
            }
        }
        return null;
    }

    public static boolean hasShortcut(Context context) {
        String AUTHORITY = getAuthorityFromPermission(context, "permission.READ_SETTINGS");
        Ln.d("shortcut AUTHORITY is %s", AUTHORITY);
        Uri CONTENT_URI = Uri.parse("content://" + AUTHORITY + "/favorites?notify=true");
        Cursor c = context.getContentResolver().query(CONTENT_URI, new String[]{"title"}, "title=?", new String[]{context.getResources().getString(R.string.app_name)}, null);
        try {
            if (c != null && c.getCount() > 0) {
                Ln.d("find shortcut");
                return true;
            }
            Ln.d("not find shortcut");
            return false;
        } finally {
            if (c != null)
                c.close();
        }
    }

    public static String getSign(Context context) {
        PackageInfo pi;
        try {
            pi = context.getPackageManager().getPackageInfo(context.getPackageName(), PackageManager.GET_SIGNATURES);
            String md5 = Md5Util.getBytesMD5String(pi.signatures[0].toByteArray());
            Ln.d("sign md5 is %s", md5);
            return md5;
        } catch (Exception e) {
            Ln.e(e);
        }
        return null;
    }

    public static boolean isOriginal(Context context) {
        if (IsOrignal == null) {
            String md5 = getSign(context);
            IsOrignal = (PUBLIC_SIGN.equals(md5) || AMAZON_SIGN.equals(md5)) && context.getPackageName().equals(PACKAGE_NAME);
        }
        return IsOrignal;
    }

    public static boolean canCreateShort() {
        if (Build.DEVICE.startsWith("mx") || Build.DEVICE.startsWith("MX")) {
            return false;
        }
        Intent home = new Intent(Intent.ACTION_MAIN);
        home.addCategory(Intent.CATEGORY_HOME);
        PackageManager pm = ApplicationContext.getContext().getPackageManager();
        ResolveInfo ri = pm.resolveActivity(home, PackageManager.MATCH_DEFAULT_ONLY);
        if (ri == null) {
            return false;
        }

        Ln.e("resolve home packagename: " + ri.activityInfo.packageName + ", DEVICE: " + Build.DEVICE);
        if (ri.activityInfo.packageName == null) {
            return false;
        }
        if (ri.activityInfo.packageName.contains("miui")) {
            return false;
        }

        return true;
    }

    public static String getDeviceManufactureName() {
        String s = Build.MANUFACTURER;
        String s1 = Build.MODEL;
        if (!s1.startsWith(s))
            s1 = (new StringBuilder()).append(s).append(" ").append(s1).toString();
        return s1;
    }

    /**
     * 和cobub那边使用同一个deviceId获取方式
     *
     * @return
     */
    public static String getDeviceId() {
        return Util.getDeviceId(ApplicationContext.getContext());
    }

    public static Map<String, String> getCupInfo() {
        String str1 = "/proc/cpuinfo";
        Map<String, String> cpuInfo = new HashMap<String, String>();
        try {
            FileReader fr = new FileReader(str1);
            BufferedReader br = new BufferedReader(fr);
            String line = null;
            while ((line = br.readLine()) != null) {
                String[] lines = line.split(":");
                if (lines != null && lines.length > 1) {
                    cpuInfo.put(lines[0].trim().toLowerCase(), lines[1].trim().toLowerCase());
                }
            }
            br.close();
        } catch (IOException e) {
            Ln.e(e);
        }
        return cpuInfo;
    }

    public static boolean hasMarketApp() {
        Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("market://details?id=" + ApplicationContext.getPackageName()));
        ResolveInfo ri = ApplicationContext.getContext().getPackageManager().resolveActivity(intent, 0);
        return ri != null && ri.activityInfo != null;
    }

    public static boolean isAppInstalled(String packageName) {
        PackageManager packagemanager = ApplicationContext.getContext().getPackageManager();
        try {
            PackageInfo packageinfo = packagemanager.getPackageInfo(packageName, 0);
            return packageinfo != null;
        } catch (NameNotFoundException namenotfoundexception) {
            return false;
        }
    }

    public static int getMaxHeapSize() {
        int heapSize = 0;
        try {
            Class<?> classType = Class.forName("android.os.SystemProperties");
            Method getMethod = classType.getDeclaredMethod("get", new Class<?>[]{String.class});
            String value = (String) getMethod.invoke(classType, new Object[]{"dalvik.vm.heapsize"});
            heapSize = Integer.parseInt(value.substring(0, value.indexOf("m"))) * 1024 * 1024;
            // Ln.d("DataBuffer heapSize:" + heapSize);
        } catch (Exception e) {
            Ln.e(e);
            return 0;
        }
        return heapSize;
    }

    public static int getProcessDirtySize(int pid) {
        ActivityManager activityManager = (ActivityManager) ApplicationContext.getContext().getSystemService(ApplicationContext.getContext().ACTIVITY_SERVICE);
        int[] pids = new int[]{pid};
        Debug.MemoryInfo memoryInfo = activityManager.getProcessMemoryInfo(pids)[0];
        return memoryInfo == null ? 0 : (memoryInfo.getTotalPrivateDirty() * 1024);
    }

    public static int getAvailableMemorySize() {
        return getMaxHeapSize() - getProcessDirtySize(android.os.Process.myPid());
    }

    public static final String getValueFromSystemProp(String key) {
        String value = null;
        try {
            Class<?> classType = Class.forName("android.os.SystemProperties");
            Method getMethod = classType.getDeclaredMethod("get", new Class<?>[]{String.class});
            value = (String) getMethod.invoke(classType, new Object[]{key});
        } catch (Exception e) {
            Ln.e(e);
        }
        return value;
    }

    public static List<String> getDnsServers() {
        List<String> dnsServers = new ArrayList<>();
        String dns1 = getValueFromSystemProp("net.dns1");
        if (!TextUtils.isEmpty(dns1)) {
            dnsServers.add(dns1);
        }
        String dns2 = getValueFromSystemProp("net.dns2");
        if (!TextUtils.isEmpty(dns2)) {
            dnsServers.add(dns2);
        }
        return dnsServers;
    }
}
